const {
  $Toast
} = require('../../dist/base/index');
const db = wx.cloud.database()
const app = getApp()
const genId = require("../../utils/genId.js")

Page({
  data: {
    address: {}
  },
  onLoad: function(options) {
    if (options.address) {
      this.setData({
        address: JSON.parse(options.address)
      })
    }
  },
  //表单提交
  formSubmit: function(e) {
    let that = this
    let item = e.detail.value
    if (!item.address_name || !item.address_detail) {
      $Toast({
        content: '内容不能为空',
        image: '../../images/icon/despise.png'
      });
      return
    }
    if (app.globalData.group) { //有组
      if (JSON.stringify(that.data.address) == '{}') { //添加
        this.addAddress(app.globalData.group._id, item.address_name, item.address_detail)
      } else { //修改
        if (that.judgeChange(item)) {
          wx.cloud.callFunction({
            name: 'updateAddress',
            data: {
              addressId: that.data.address._id,
              address_name: item.address_name,
              address_detail: item.address_detail
            }
          }).then(res => {
            if (res.result.stats.updated == 1) {
              that.backManage('修改成功')
            }
          })
        }
      }
    } else { //没有组
      if (JSON.stringify(that.data.address) == '{}') { //添加
        this.addAddress(null, item.address_name, item.address_detail)
      } else { //修改
        if (that.judgeChange(item)) {
          db.collection('address').doc(that.data.address._id).update({
            data: {
              address_name: item.address_name,
              address_detail: item.address_detail
            }
          }).then(res => {
            if (res.stats.updated == 1) {
              that.backManage('修改成功')
            }
          })
        }
      }
    }
  },
  //添加地址并返回
  addAddress(groupId, address_name, address_detail) {
    let that = this
    db.collection('address').add({
      data: {
        _id: genId.wxuuid(),
        address_name: address_name,
        address_detail: address_detail,
        groupId: groupId
      }
    }).then(res => {
      if (res._id) {
        that.backManage('添加成功')
      }
    })
  },
  //返回出入口管理
  backManage(title) {
    app.globalData.flushView = true
    app.globalData.flushExport = true
    app.globalData.flushManage = true
    app.globalData.flushQrCode = true
    wx.switchTab({
      url: '/pages/manage/manage',
      success: function(res) {
        wx.showToast({
          title: title,
          icon: 'success',
          duration: 2000
        })
      }
    })
  },
  judgeChange(item) {
    if (item.address_name == this.data.address.address_name && item.address_detail == this.data.address.address_detail) {
      $Toast({
        content: '内容并未修改',
        image: '../../images/icon/despise.png'
      });
      return false
    }
    return true
  }
})